package com.cjjd.c.feature.subscribe.write_order;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.cjjd.c.EventBusKeys;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.ActionBarActivity;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.subscribe.BookOrderModel;
import com.cjjd.c.bean.subscribe.GenBookOrderModel;
import com.cjjd.c.feature.home.chekin.checklist_detail.CheckinDetailActivity;
import com.cjjd.c.feature.home.chekin.pay.PayPledgeActivity;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.CommonUtil;
import com.cjjd.c.utils.DateTimeUtil;
import com.cjjd.c.utils.DialogUtil;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/11/30.
 * <p/>
 * 描  述：订单下单页面
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class WriteOrderActivity extends ActionBarActivity {


    @Bind(R.id.tv_time_for_settle_leave)
    TextView tv_time_for_settle_leave;
    @Bind(R.id.tv_hotel_name)
    TextView tv_hotel_name;
    @Bind(R.id.tv_hotel_style)
    TextView tv_hotel_style;

    @Bind(R.id.tv_room_num)
    TextView tvRoomNum;
    @Bind(R.id.lv_book_order)
    ListView lv_book_order;


    @Bind(R.id.tv_pay_type)
    TextView tv_pay_type;
    @Bind(R.id.tv_selecetable)
    TextView tv_selecetable;

    @Bind(R.id.et_hkb_use)
    EditText et_hkb_use;
    @Bind(R.id.tv_hkb_have)
    TextView tvHkbHave;

    @Bind(R.id.tv_pay_num)
    TextView tvPayNum;
    @Bind(R.id.tv_pay)
    TextView tvPay;


    private BookOrderModel bookOrderModel;
    private String hotelUuid;
    private String roomTypeUuid;
    private String priceTypeUuid;
    private String startDate;
    private String endDate;
    private List<String> nameList = new ArrayList<>();
    private int totalDays;
    private String hkGoldNum;
    private double totalMoney;

    private BookOrderAdapter bookOrderAdapter;
    // 入住人数
    private List<String> bookOderItemList = new ArrayList<>();


    private ArrayList<String> roomList = new ArrayList<>();
    private ArrayList<String> payTypeList = new ArrayList<>();
    private String payType = "1";


    @Override
    public Object getTitleString() {
        return "北京希尔顿酒店";
    }

    @Override
    public int getContentView() {
        return R.layout.activity_write_order;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        bookOrderModel = (BookOrderModel) getIntent().getSerializableExtra("bookOrderModel");
        hotelUuid = getIntent().getStringExtra("hotelUuid");
        roomTypeUuid = getIntent().getStringExtra("roomTypeUuid");
        priceTypeUuid = getIntent().getStringExtra("priceTypeUuid");

        initView();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    private void initView() {

        if (bookOrderModel != null) {

            tv_hotel_name.setText(bookOrderModel.hotelName);
            tv_time_for_settle_leave.setText("入离店日期: " + bookOrderModel.startDate + "-" + bookOrderModel.endDate);
            totalDays = DateTimeUtil.getBetweenDays(bookOrderModel.endDate, bookOrderModel.startDate, "yyyy-MM-dd");//2017-11-11
            tv_hotel_style.setText(bookOrderModel.roomTypeDesc);

            if (bookOrderModel.getIsStorePay()) {
                tv_selecetable.setVisibility(View.VISIBLE);
            } else {
                tv_selecetable.setVisibility(View.GONE);
            }
            tvHkbHave.setText("拥有" + bookOrderModel.hkGoldNum + "个");
            startDate = bookOrderModel.startDate;
            endDate = bookOrderModel.endDate;

        }

        for (int i = 0; i < 10; i++) {
            roomList.add(i + 1 + "间");
        }

        payTypeList.add("在线支付");
        payTypeList.add("到店支付");


        bookOrderAdapter = new BookOrderAdapter(mContext);
        bookOrderAdapter.setData(bookOderItemList);
        lv_book_order.setAdapter(bookOrderAdapter);


        et_hkb_use.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (bookOderItemList.size() <= 0) {
                    LogUtil.e("xyd","没选择房间数");
                    return;
                } else {
                    hkGoldNum = s.toString().trim();
                    try {
                        Double.parseDouble(hkGoldNum);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        hkGoldNum = "0";
                    }

                    if (Double.parseDouble(hkGoldNum) > bookOrderModel.getHkGoldNum()) {
                        ToastUtil.showShortToast(mContext, "可用好客币不足");
                        et_hkb_use.setText(s.toString().substring(0, s.toString().length() - 1)+"");
                        return;
                    }

                    totalMoney = totalMoney - Double.parseDouble(hkGoldNum);
                    tvPayNum.setText("￥ " + totalMoney);
                }
            }
        });

    }


    @OnClick({R.id.tv_room_num, R.id.tv_pay, R.id.tv_selecetable})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_room_num:

                DialogUtil.showListDialog(mContext, "请选择房间数", roomList, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tvRoomNum.setText(which + 1 + "间");
                        if (bookOderItemList.size() > 0) {
                            bookOderItemList.clear();
                        }
                        for (int i = 0; i <= which; i++) {
                            bookOderItemList.add("1");
                        }
                        bookOrderAdapter.notifyDataSetChanged();
                        CommonUtil.setListViewHeightBasedOnChildren(lv_book_order);

                        // 计算房价并显示
                        totalMoney = 0;
                        TreeMap<String, String> entries = bookOrderModel.prices;
                        Set<String> dateSet = entries.keySet();
                        for (String key : dateSet) {
                            String everyPrice = entries.get(key);
                            totalMoney += Double.parseDouble(everyPrice) * bookOderItemList.size();
                        }
                        tvPayNum.setText("￥ " + totalMoney);

                    }
                });

                break;

            case R.id.tv_selecetable:

                DialogUtil.showListDialog(mContext, "请选择支付方式", payTypeList, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tv_pay_type.setText(payTypeList.get(which));
                        if (which == 0) {
                            payType = "1";  // 在线支付
                            tvPay.setText("立即支付");
                        } else {
                            payType = "2";  // 到店支付
                            tvPay.setText("到店支付");

                        }
                    }
                });

                break;
            case R.id.tv_pay:


                if (check()) {
                    genBookOrder();
                }

                break;


        }
    }


    private boolean check() {

        if (bookOderItemList.size() <= 0) {
            ToastUtil.showShortToast(mContext, "请选择入住人数");
            return false;
        }

        //获取并检测房客姓名
        if (nameList.size() > 0) {
            nameList.clear();
        }
        SparseArray<String> nameArray = bookOrderAdapter.getNameArray();
        int nameArrayLength = nameArray.size();
        if (nameArrayLength < bookOderItemList.size()) {
            ToastUtil.showShortToast(mContext, "请完成入住人姓名输入");
            return false;
        }
        for (int i = 0; i < nameArrayLength; i++) {
            if (TextUtils.isEmpty(nameArray.get(i))) {
                ToastUtil.showShortToast(mContext, "请完成入住人姓名输入");
                return false;
            }
            nameList.add(nameArray.get(i));
        }
        //LogUtil.e("xyd",JsonUtils.convertListParam(nameList));


        // 使用好客币数量
        hkGoldNum = et_hkb_use.getText().toString().trim();
        try {
            Double.parseDouble(hkGoldNum);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            hkGoldNum = "0";
        }
        LogUtil.e("xyd", "好客币使用数量: " + hkGoldNum);

        // 计算总房价
        totalMoney = 0;
        TreeMap<String, String> entries = bookOrderModel.prices;
        Set<String> dateSet = entries.keySet();
        for (String key : dateSet) {
            String everyPrice = entries.get(key);
            //LogUtil.e("xyd", "key:" + key + "  ****  value:" + entries.get(key));
            totalMoney += Double.parseDouble(everyPrice) * bookOderItemList.size();
        }
        totalMoney = totalMoney - Double.parseDouble(hkGoldNum);
        //LogUtil.e("xyd", "totalMoney is:  " + totalMoney);

        return true;
    }

    private void genBookOrder() {

        /*token	String	会员调用登录接口后，返回的唯一标识
        sessionId	String	会员调用登录接口后，返回的sessionId
        hotelUuid	String	酒店uuid
        roomTypeUuid	String	房型uuid
        priceTypeUuid	String	房型类型uuid
        startDate	String	开始时间
        endDate	String	结束时间
        arriveTime	String	到店时间
        mobile	String	手机号
        nameList	List<String>	入住人名称集合
        remarks	String	备注
        payType	String	支付方式 1在线支付 2到店面付
        hkGoldNum	int	可用好客币数量
        totalMoney	double	总金额（用于验证计算是否一致）*/

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("hotelUuid", hotelUuid);    //先写死
        h1.put("roomTypeUuid", roomTypeUuid);    //房型
        h1.put("priceTypeUuid", priceTypeUuid);    //房间类型
        h1.put("startDate", startDate);    //开始时间
        h1.put("endDate", endDate);    //结束时间

        //h1.put("arriveTime", "2017-12-22 18:00");   // 这个参数改为非必填
        //h1.put("mobile", "15611552330");            // 这个参数改为非必填
        h1.put("nameList", JsonUtils.convertListParam(nameList));
        h1.put("payType", payType);
        h1.put("hkGoldNum", hkGoldNum);
        h1.put("totalMoney", totalMoney + "");

        Call<HttpResult<GenBookOrderModel>> call = service.genBookOrder(JsonUtils.convertParam("genBookOrder", h1));
        call.enqueue(new CallbackImpl<GenBookOrderModel>() {
            @Override
            public void responseSuccess(Call<HttpResult<GenBookOrderModel>> call, Response<HttpResult<GenBookOrderModel>> response) {


                GenBookOrderModel genBookOrderBean = response.body().getData();
                // 生成预订单成功
                if ("1".endsWith(payType)) { // 在线支付
                    Intent intent = new Intent(mContext, PayPledgeActivity.class);
                    intent.putExtra("fromPage", PayPledgeActivity.PayPreOrder);
                    intent.putExtra("genBookOrder", genBookOrderBean);
                    mContext.startActivity(intent);

                } else if ("2".endsWith(payType)) {  // 到店支付
                    Intent intent = new Intent(mContext, CheckinDetailActivity.class);
                    intent.putExtra("mainUuid", genBookOrderBean.orderUuid);
                    mContext.startActivity(intent);
                    EventBus.getDefault().post(EventBusKeys.finishPreOrder);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        if (EventBusKeys.finishPreOrder.equals(event)) {
            finish();
        }
    }




}

